import hashin
import json
import plette
import ssl
import traceback
from urllib.error import URLError
from poetry.factory import Factory


def get_dependency_hash(dependency_name, dependency_version, algorithm,
                        index_url=hashin.DEFAULT_INDEX_URL):
    try:
        hashes = hashin.get_package_hashes(
            dependency_name,
            version=dependency_version,
            algorithm=algorithm,
            index_url=index_url
        )
        return json.dumps({"result": hashes["hashes"]})
    except hashin.PackageNotFoundError as e:
        return json.dumps({
            "error": repr(e),
            "error_class:": e.__class__.__name__,
            "trace:": ''.join(traceback.format_stack())
        })
    except (URLError, ssl.SSLError) as e:
        # Handle SSL certificate verification errors
        error_msg = str(e)
        if "CERTIFICATE_VERIFY_FAILED" in error_msg:
            return json.dumps({
                "error": "CERTIFICATE_VERIFY_FAILED: " + error_msg,
                "error_class:": e.__class__.__name__,
                "trace:": ''.join(traceback.format_stack())
            })
        # Re-raise if it's not a certificate verification error
        raise


def get_pipfile_hash(directory):
    with open(directory + '/Pipfile') as f:
        pipfile = plette.Pipfile.load(f)

    return json.dumps({"result": pipfile.get_hash().value})


def get_pyproject_hash(directory):
    p = Factory().create_poetry(directory)

    return json.dumps({"result": p.locker._get_content_hash()})
